<?php
namespace addons\service\library;

use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\Request;
use think\Exception;

class Pay
{
    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws Exception
     */
    public static function payOrder($order, $paytype, $uid, $types)
    {
        switch ($paytype) {
            case 0:
                $method='miniapp';
                $type = 'wechat';
                break;
            case 1:
                $method='app';
                $type = 'wechat';
                break;
            case 2:
                $method='mp';
                $type = 'wechat';
                break;
            case 3:
                $method='app';
                $type = 'alipay';
                break;
            default:
                $method='miniapp';
                $type = 'wechat';
        }
        $order['type'] = $type;
        $request = Request::instance();
        $domain=$request->domain();
        if($types == 0){
            $order['notifyurl'] = $domain.'/addons/service/notify/notifyx/paytype/'.$type;
        }else{
            $order['notifyurl'] = $domain.'/addons/service/notify/notify/paytype/'.$type;
        }
        $order['returnurl'] = $domain.'/addons/service/notify/returnx/paytype/'.$type;
        $order['method'] = $method;
        $userInfo = \app\api\model\service\UserInfo::where('user_id',$uid)->field('id,user_openid,skill_openid,shop_openid,is_skill,is_shop')->find();
        switch ($types){
            case 0:
                $openid = $userInfo['user_openid'];
                break;
            case 1:
                $openid = $userInfo['skill_openid'];
                break;
            case 2:
                $openid = $userInfo['shop_openid'];
                break;
            default:
                $openid = $userInfo['user_openid'];
        }
        $order['openid'] = $openid;
        $info = get_addon_info('epay');
        if (!$info || !$info['state']) {
            throw new Exception("请确保微信支付宝整合插件已安装并启用");
        }
        if($types == 0){
            $re = \addons\epay\library\Service::submitOrder($order);
        }else{
            $wxPay = new WxPay();
            $re = $wxPay->pay(['type'=>$types,'body'=>$order['title'],'out_trade_no'=>$order['orderid'],'total_fee'=>intval($order['amount']*100),'notify_url'=>$order['notifyurl'],'openid'=>$openid]);
        }
        return $re;
    }
}